package com.qf.kdxf.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.qf.kdxf.entity.ResultData;
import com.qf.kdxf.entity.naturallanguage.JsonParse;
import com.qf.kdxf.service.NaturalLanguageService;
import com.qf.kdxf.util.NaturalLanguageUtil;
import org.springframework.stereotype.Service;

import java.util.Base64;

@Service
public class NaturalLanguageServiceImpl implements NaturalLanguageService {

    private static final Gson gson = new Gson();

    @Override
    public ResultData getTranslation(String form, String to, String text) {
        JSONObject jsonObject = null;
        try{
            String result = NaturalLanguageUtil.doRequest(form,to,text);
            JsonParse jsonParse = gson.fromJson(result, JsonParse.class);
            String textBase64 = new String(Base64.getDecoder().decode(jsonParse.getPayload().getResult().getText()),"UTF-8");
            jsonObject = JSON.parseObject(textBase64);
            System.out.println(jsonObject);
            System.out.println(jsonObject.getString("trans_result"));

        }catch (Exception e){
            e.printStackTrace();
            return new ResultData(500,"翻译失败",null);
        }
        return new ResultData(200,"翻译成功",jsonObject.getString("trans_result"));
    }
}
